import editForm from "../form.vue";
import detail from "../detail.vue";
import log from "../log.vue";
import { message } from "@/utils/message";
import {
  saveJob,
  getJobList,
  getInstancePage,
  onRetryInstance,
  type InstanceInfo,
  onStopInstance
} from "@/api/job";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h, toRaw } from "vue";
import { deviceDetection } from "@pureadmin/utils";
import type { PaginationProps } from "@pureadmin/table";
import { toBackendPageObj, toFrontendPageObj } from "@/api/utils";
import { formatDate } from "@/utils/formatter";

export function useAppInfo() {
  const form = reactive({
    appId: "",
    jobId: "",
    statuses: []
  });

  const formRef = ref();
  const jobList = ref([]);
  const dataList = ref([]);
  const loading = ref(true);
  ref({});
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    pageSizes: [10, 15, 20],
    background: true,
    small: false
  });

  const columns: TableColumnList = [
    {
      label: "App名称",
      prop: "appName",
      width: 150,
      align: "left"
    },
    {
      label: "任务名称",
      prop: "jobName",
      width: 200,
      align: "left"
    },
    {
      label: "实例ID",
      prop: "id",
      width: 200,
      align: "left"
    },
    {
      label: "状态",
      prop: "status",
      formatter: ({ status }) => {
        switch (status) {
          case "WAITING_DISPATCH":
            return "等待派发";
          case "WT_WORKER_RCV":
            return "等待Worker接收";
          case "RUNNING":
            return <span style="color: blue">运行中</span>;
          case "FAILED":
            return <span style="color: red">失败</span>;
          case "SUCCEED":
            return <span style="color: green">成功</span>;
          case "CANCELED":
            return "取消";
          case "STOPPED":
            return "手动停止";
          default:
            return "未知状态";
        }
      },
      minWidth: 250
    },
    {
      label: "触发时间",
      minWidth: 120,
      prop: "actualTriggerTime",
      formatter: ({ actualTriggerTime }) => formatDate(actualTriggerTime)
    },
    {
      label: "结束时间",
      minWidth: 120,
      prop: "finishedTime",
      formatter: ({ finishedTime }) => formatDate(finishedTime)
    },
    {
      label: "操作",
      fixed: "right",
      width: 280,
      slot: "operation"
    }
  ];

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  function handleSelectionChange(val) {
    pagination.currentPage = val;
    onSearch();
  }

  function appSelectionChanged() {
    jobList.value = [];
    form.jobId = null;
    if (form.appId) {
      getJobList({ appId: form.appId }).then(res => {
        jobList.value = res;
      });
    }
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    const data = await getInstancePage({
      ...toRaw(form),
      ...toBackendPageObj(pagination)
    });
    dataList.value = data.records;
    toFrontendPageObj(data, pagination);

    setTimeout(() => {
      loading.value = false;
    }, 300);
  }

  function openDialog(title = "新增", row?: InstanceInfo) {
    addDialog({
      title: `${title}任务信息`,
      props: {
        formInline: {
          id: row?.id ?? "",
          appId: row?.appId ?? "",
          jobName: row?.jobName ?? "",
          jobDescription: row?.jobDescription ?? "",
          jobParams: row?.jobParams ?? "",
          timeExpressionType: row?.timeExpressionType ?? "",
          timeExpression: row?.timeExpression ?? "",
          processorType: row?.processorType ?? "",
          processorInfo: row?.processorInfo ?? "",
          status: row?.status ?? "NORMAL",
          instanceTimeLimit: row?.instanceTimeLimit ?? 0,
          retryTimes: row?.retryTimes ?? 0,
          lifecycleRange: row?.lifecycleRange ?? [],
          logConfig: row?.logConfig ?? {}
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as InstanceInfo;
        function save() {
          if (title === "新增") {
            saveJob(curData)
              .then(() => {
                message(`您${title}了任务名称为${curData.jobName}的这条数据`, {
                  type: "success"
                });
                done(); // 关闭弹框
                onSearch(); // 刷新表格数据
              })
              .catch(error => {
                console.log("error", error);
                message(error.message, {
                  type: "error"
                });
              });
          } else {
            saveJob(curData)
              .then(() => {
                message(
                  `您${title}了业务域名称为${curData.jobName}的这条数据`,
                  {
                    type: "success"
                  }
                );
                done(); // 关闭弹框
                onSearch(); // 刷新表格数据
              })
              .catch(error => {
                console.log("error", error);
                message(error.message, {
                  type: "error"
                });
              });
          }
        }
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              save();
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              save();
            }
          }
        });
      }
    });
  }

  function showDetailDialog(row?: InstanceInfo) {
    addDialog({
      title: `实例详情`,
      props: {
        appId: row?.appId ?? "",
        instanceId: row?.id ?? ""
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(detail)
    });
  }

  function showLogDialog(row?: InstanceInfo) {
    addDialog({
      title: `实例日志`,
      props: row,
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(log)
    });
  }

  function handleStop(row) {
    onStopInstance(row).then(() => {
      message(`您停止了ID为${row.id}的任务实例`, {
        type: "success"
      });
      onSearch();
    });
  }

  function handleRetryInstance(row) {
    onRetryInstance(row).then(() => {
      message(`您重试了任务名称为${row.id}的这条数据`, {
        type: "success"
      });
      onSearch();
    });
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    jobList,
    columns,
    dataList,
    pagination,
    appSelectionChanged,
    /** 搜索 */
    onSearch,
    /** 重置 */
    resetForm,
    /** 新增、修改业务域 */
    openDialog,
    showDetailDialog,
    showLogDialog,
    /** 删除业务域 */
    handleStop,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    /** 实例 */
    handleRetryInstance
  };
}
